package com.projectm.common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author linyanbin
 * @date 2022/7/5 14:41
 */
@Service
public class RedisUtil {
    @Autowired
    private final RedisTemplate redisTemplate;

    public RedisUtil(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 通过key在redis中获取value
     * @Param [key]
     * @return java.lang.String
     **/
    public String getValue(String key) {
        return (String) redisTemplate.opsForValue().get(key);
    }


    /**
     * 存储验证码的key，value，并设置有效时间timeout
     * @param key
     * @param value
     * @param timeout
     */
    public void setVerificationKey(String key, Object value, long timeout) {
        // opsForValue()是用来存储字符串数据的，这里存储图片验证的UUID
        redisTemplate.opsForValue().set(key, value);
        // 设置图片的有效期为3分钟
        redisTemplate.expire(key, timeout, TimeUnit.MINUTES);
    }

    /**
     * 删除redis中的key
     * @Param [key]
     * @return boolean
     **/
    public boolean removeKey(String key) {
        if(StringUtil.isEmptyOrNull(key)) {
            return false;
        }
        return redisTemplate.delete(key);
    }
}
